package com.xxkj.drugtraceability.base

import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.IBinder
import android.text.Html
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.gyf.immersionbar.ImmersionBar
import com.xxkj.drugtraceability.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


abstract class BaseVMActivity : AppCompatActivity() {
    lateinit var mContext: Context
    open var modelCode: String = ""
    open var modelName: String = ""
    open var pageCode: String = ""
    open var pageName: String = ""
    protected inline fun <reified T : ViewDataBinding> binding(
            @LayoutRes resId: Int
    ): Lazy<T> = lazy {
        DataBindingUtil.setContentView<T>(this, resId).apply {
            lifecycleOwner = this@BaseVMActivity
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = this
        if (isImmersionBarEnabled()) {
            initImmersionBar()
        }
        startObserve()
        initView()
        initBehaviorData()
        initData()
    }
    abstract fun initView()
    abstract fun initData()
    open fun initBehaviorData() {}
    abstract fun startObserve()

    //加载框
    protected var dialog: ProgressDialog? = null
    open fun showMyDialog(msg: String?) {
        if (msg == null)
            return
        if (isDestroyed)
            return
        if (dialog == null) {
            dialog = ProgressDialog(this).apply {
                setProgressStyle(ProgressDialog.STYLE_SPINNER)
                setMessage(Html.fromHtml(msg))
//                setCancelable(false)

                isIndeterminate = true
                setCanceledOnTouchOutside(false)
            }
        }
        if (dialog?.isShowing == true)
            return
        dialog?.setMessage(msg)
        dialog?.show()
    }

    open fun dismissMyDialog() {
        dialog?.dismiss()
    }



    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            val v = currentFocus
            if (v != null)
                if (isShouldHideInput(v, ev)) {
                    hideSoftInput(v.windowToken)
                }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     */
    private fun isShouldHideInput(v: View, event: MotionEvent): Boolean {
        if (v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom: Int = top + v.getHeight()
            val right: Int = (left
                    + v.getWidth())
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     */
    private fun hideSoftInput(token: IBinder?) {
        if (token != null) {
            val im = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected open fun isImmersionBarEnabled(): Boolean {
        return true
    }

    protected open fun initImmersionBar() {
        ImmersionBar.with(this)
//                 .statusBarDarkFont(true) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .fitsSystemWindows(false)
                .keyboardEnable(true)
            .transparentStatusBar()
//                .statusBarColor(R.color.toolbar_background)
//                .navigationBarColor(R.color.virtual_buttons)
                .init()

    }




    override fun onDestroy() {
        super.onDestroy()
        dialog?.dismiss()
    }


}